using UnityEngine;

public enum PlayerState
{
    Idle,
    Walking,
    Running,
    Jumping,
    Attacking
}

public class PlayerStateMachine : MonoBehaviour
{
    private PlayerState currentState;
    private Animator animator;

    private void Start()
    {
        animator = GetComponent<Animator>();
        currentState = PlayerState.Idle;
    }

    private void Update()
    {
        HandleState();
    }

    private void HandleState()
    {
        switch (currentState)
        {
            case PlayerState.Idle:
                HandleIdleState();
                break;
            case PlayerState.Walking:
                HandleWalkingState();
                break;
            case PlayerState.Running:
                HandleRunningState();
                break;
            case PlayerState.Jumping:
                HandleJumpingState();
                break;
            case PlayerState.Attacking:
                HandleAttackingState();
                break;
        }
    }

    private void HandleIdleState()
    {
        animator.SetBool("IsWalking", false);
        animator.SetBool("IsRunning", false);
        animator.SetBool("IsJumping", false);
        if (Input.GetKey(KeyCode.W))
        {
            SetState(PlayerState.Walking);
        }
        if (Input.GetKey(KeyCode.Space))
        {
            SetState(PlayerState.Jumping);
        }
    }

    private void HandleWalkingState()
    {
        animator.SetBool("IsWalking", true);
        animator.SetBool("IsRunning", false);
        if (Input.GetKey(KeyCode.LeftShift))
        {
            SetState(PlayerState.Running);
        }
        if (!Input.GetKey(KeyCode.W))
        {
            SetState(PlayerState.Idle);
        }
    }

    private void HandleRunningState()
    {
        animator.SetBool("IsWalking", false);
        animator.SetBool("IsRunning", true);
        if (!Input.GetKey(KeyCode.LeftShift))
        {
            SetState(PlayerState.Walking);
        }
        if (!Input.GetKey(KeyCode.W))
        {
            SetState(PlayerState.Idle);
        }
    }

    private void HandleJumpingState()
    {
        animator.SetBool("IsJumping", true);
        if (Input.GetKey(KeyCode.W))
        {
            SetState(PlayerState.Walking);
        }
        if (Input.GetKey(KeyCode.LeftShift))
        {
            SetState(PlayerState.Running);
        }
    }

    private void HandleAttackingState()
    {
        animator.SetTrigger("Attack");
    }

    private void SetState(PlayerState newState)
    {
        if (currentState != newState)
        {
            currentState = newState;
            OnStateChanged();
        }
    }

    private void OnStateChanged()
    {
        Debug.Log("玩家当前状态: " + currentState);
    }
}
